﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using CDSBDemandControl.Presenter;
using CDSBDemandControl.Model;
using System.Data;
using System.Drawing;

namespace CDSBDemandControl.View.Web.PaginasInternas
{
    public partial class Alocacao : System.Web.UI.Page, IDiscriminatorDemand
    {
        private Presenter.DiscriminatorDemand Presenter;
        public string caption = "Previsão de Alocação referente ao mês {0}.";
        public int[] array;
        DateTime inicioPeriodo;
        public IEnumerable<DemandModel> demandas;

        protected void Page_Load(object sender, EventArgs e)
        {
            Response.Cache.SetExpires(DateTime.Now.Subtract(new TimeSpan(24, 0, 0)));
            Response.Cache.SetCacheability(HttpCacheability.NoCache);

            if (!this.IsPostBack || this.Session["Presenter"] == null)
            {
                this.Presenter = new DiscriminatorDemand(this);

                this.Session["Presenter"] = this.Presenter;

                if (!this.IsPostBack)
                    this.ListarAlocacao();
            }
            else
            {
                this.Presenter = (Presenter.DiscriminatorDemand)this.Session["Presenter"];
                this.Presenter.ResetView(this);
            }
        }

        protected void cboMonths_SelectedIndexChanged(object sender, EventArgs e)
        {
            string[] data = (sender as DropDownList).SelectedItem.Text.Split('/');
            Response.Redirect(string.Format("Alocacao.aspx?year={0}&month={1}",data[1],data[0]));
        }

        private void ListarAlocacao()
        {
            this.Presenter.ListarPrevisaoAlocacao();
        }

        public class DeveloperTasksByDay 
        {
            public string DeveloperName { get; set; }
            public List<DateTime> Datas { get; set; }
            public List<DemandModel> Demandas { get; set; }
        }

        void IDiscriminatorDemand.ExibirAlocacao(IEnumerable<DemandModel> demandModels)
        {
            this.parent.Controls.Clear();

            this.PreencherCombo(demandModels);
            if (Request.QueryString["year"] != null && Request.QueryString["month"] != null)
            {
                inicioPeriodo = new DateTime(Convert.ToInt32(Request.QueryString["year"]), Convert.ToInt32(Request.QueryString["month"]), 1);
                cboMonths.SelectedValue = Request.QueryString["month"] + "/" + Request.QueryString["year"];
            }
            else
            {
                inicioPeriodo = new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1);
                cboMonths.SelectedValue = inicioPeriodo.Month + "/" + inicioPeriodo.Year;
            }
               
            this.ExibirObservacao(string.Format(caption, inicioPeriodo.ToString("MMM/yyyy")));

            demandModels = 
                demandModels.ToList().FindAll(delegate(DemandModel d) 
                {
                    if (d.Start.HasValue)
                    {
                        d.EstimatedStart = d.Start;
                    }
                    if (d.Conclude.HasValue)
                    {
                        d.EstimatedConclude = d.Conclude;
                    }

                    return inIntervalo(d.EstimatedStart, d.EstimatedConclude, inicioPeriodo) 
                        && 
                        ((d.State != "Cancelada") || (d.State == "Cancelada" && d.UsedHours != 0));
                }
            );

            demandas = demandModels;

            List<DeveloperTasksByDay> lst = new List<DeveloperTasksByDay>();
            demandModels.ToList().ForEach(delegate (DemandModel d)
            {
                List<DateTime> datas = new List<DateTime>();
                for (int i = 0; i <= (d.EstimatedConclude.Value - d.EstimatedStart.Value).Days; i++)
                {
                    datas.Add(d.EstimatedStart.Value.AddDays(i));
                }

                DeveloperTasksByDay item = null;

                if ((item = lst.Find(delegate(DeveloperTasksByDay dev) { return dev.DeveloperName == (this.Presenter.FindDeveloperOf(d.Revision) ?? new DeveloperModel() { DeveloperName = d.AssignedTo }).DeveloperName; })) == null)
                    lst.Add(item = new DeveloperTasksByDay() { DeveloperName = (this.Presenter.FindDeveloperOf(d.Revision) ?? new DeveloperModel() { DeveloperName = d.AssignedTo }).DeveloperName, Datas = datas, Demandas = new List<DemandModel>() });
                else
                    item.Datas.AddRange(datas);

                item.Demandas.Add(d);
            }
            );

            demandModels = from d in demandModels
                           orderby d.Project, d.ID
                           select d;

            DataTable dt = new DataTable("demandas");
            dt.Columns.Add("TEAMPROJECT");
            dt.Columns.Add("PROJECT");
            dt.Columns.Add("ID");

            for (int i = 1; i <= System.DateTime.DaysInMonth(inicioPeriodo.Year, inicioPeriodo.Month); i++)
            {
                dt.Columns.Add(""+i);
            }

            DemandModel mdy = demandModels.ToList().Find(delegate(DemandModel md) { return md.ID == "16200"; });

            DataRow row = null;
            foreach (DemandModel model in demandModels)
            {
                row = dt.NewRow();
                row["TEAMPROJECT"] = this.RetornaTeamProject(model.Project);
                row["PROJECT"] = model.Project;
                row["ID"] = model.ID;                

                for (int i = 1; i <= System.DateTime.DaysInMonth(inicioPeriodo.Year, inicioPeriodo.Month); i++)
                {
                    DateTime dataColuna = inicioPeriodo.AddDays(i - 1);
                    bool estaPeriodo = inData(model.EstimatedStart, model.EstimatedConclude, dataColuna);

                    DeveloperTasksByDay desenvolvedor = lst.Find(
                            delegate(DeveloperTasksByDay dev)
                            {
                                return dev.DeveloperName == (this.Presenter.FindDeveloperOf(model.Revision) ?? new DeveloperModel() { DeveloperName = model.AssignedTo }).DeveloperName;
                            }
                            );

                    model.Title = "8h";

                    List<DemandModel> count = new List<DemandModel>();
                    for (int k = 0; k <
                        (
                        (
                            count = desenvolvedor.Demandas.FindAll
                        (delegate(DemandModel task)
                        {
                            return inData(task.EstimatedStart, task.EstimatedConclude, dataColuna);
                        })).Count

                        );
                        k++)
                    {
                        if (count[k].IsSimultaneous)
                        {
                            if (k != count.Count - 1)
                            {
                                count[k].Title = "" + (8 / count.Count);
                            }
                            else
                            {
                                int arredondamento = (8 - ((8 / count.Count) * (count.Count - 1)));
                                count[k].Title = "" + arredondamento;
                            }
                        }
                        else 
                        {
                            count[k].Title = "8";
                        }
                    }

                    if (estaPeriodo && !this.Presenter.getFeriados().Contains(dataColuna.Date) && dataColuna.DayOfWeek != DayOfWeek.Saturday && dataColuna.DayOfWeek != DayOfWeek.Sunday)
                    {
                        ///if ((model.State != "Ativa" && model.State != "Em Fila") && model.IsSimultaneous)
                        if (model.State != "Ativa" && model.State != "Em Fila")
                            row[i + 2] = model.Title;
                        else
                            row[i + 2] = 8;
                    }                    
                }

                dt.Rows.Add(row);
            }

            DataView dv = new DataView(dt);
            dv.Sort = "TEAMPROJECT,PROJECT,ID";

            var demandGroups =
                       from d in demandModels                       
                       group d by d.Project into g
                       select new { Project = g.Key, Demands = g };

            int subGroups = demandGroups.ToList().Count;

            GridView grd = null;

            AdicionarGridTotalGeral(dt, grd);
            AdicionarGridTotalAtiva(dt, grd, demandModels);
            DataView devForce = AdicionarGridForcaDesenvolvimento(grd);
            AdicionarGridHorasDisponiveis(dt, grd);

            AdicionarGrafico(dt, devForce);

            string oldTeamProject = string.Empty;
            for (int i = 0; i < subGroups; i++)
            {
                grd = new GridView();
                grd.Attributes.Add("bordercolor", "#000000");
                grd.AutoGenerateColumns = true;
                grd.ID = demandGroups.ToList()[i].Demands.First().Project;
                dt.DefaultView.RowFilter = "PROJECT = '"+ grd.ID + "'";
                grd.RowDataBound += new GridViewRowEventHandler(grd_RowDataBound);
                grd.DataSource = dt.DefaultView;
                grd.ShowFooter = true;
                array = new int[dt.Columns.Count];
                grd.DataBind();       

                if (dt.DefaultView[0][0].ToString() != oldTeamProject)
                {
                    oldTeamProject = dt.DefaultView[0][0].ToString();
                    if (!string.IsNullOrEmpty(oldTeamProject)) 
                    { 
                        this.parent.Controls.Add(new LiteralControl("</div>")); 
                        this.parent.Controls.Add(new LiteralControl("<br/><br/>")); 
                    }
                    string span = "<div style='width:100%; background-color:#E1ECFC; border: solid; border-width:1px; border-color:#000000; font-family:Verdana;font-size:Small;font-weight:bold;text-align:left;'>TEAM PROJECT {0}";
                    this.parent.Controls.Add(new LiteralControl(string.Format(span, dt.DefaultView[0][0].ToString()) + "<br/><br/>"));
                }
                
                grd.HorizontalAlign = HorizontalAlign.Center;
                this.parent.Controls.Add(grd);
                this.parent.Controls.Add(new LiteralControl("<br/>"));
                
            }

            this.parent.Controls.Add(new LiteralControl("</div>"));

            foreach (Control ctr in this.parent.Controls)
            {
                if (ctr is GridView)
                    ctr.EnableViewState = false;
            }

            // Exibe a data da última atualização
            (this.Master.FindControl("LblUltimoUpdate") as Label).Text = "Última atualização em: " + this.Presenter.DemandListLastUpdate.ToShortDateString() + " as " + this.Presenter.DemandListLastUpdate.ToShortTimeString();
        }

        private void AdicionarGrafico(DataTable demandas, DataView devForce)
        {
            List<DateTime> feriados = this.Presenter.getFeriados();
            List<string> lines = new List<string>() { "Alocacao", "ForcaDesenvolvimento" };

            for (int i = 0; i < 2; i++)
            {
                chartAlocDisp.Series.Add(lines[i]);
                chartAlocDisp.Series[lines[i]].ChartArea = "MainChart";
                chartAlocDisp.Series[lines[i]].ChartType = System.Web.UI.DataVisualization.Charting.SeriesChartType.Line;

                for (int j = 1; j <= System.DateTime.DaysInMonth(inicioPeriodo.Year, inicioPeriodo.Month); j++)
                {
                    DateTime collumnDate = inicioPeriodo.AddDays(j - 1);

                    System.Web.UI.DataVisualization.Charting.DataPoint dt;
                    if (i == 0)
                    {
                        int aux = 0;
                        foreach (DataRow item in demandas.Rows)
                        {
                            string value = item[j + 2].ToString();
                            if (!string.IsNullOrEmpty(value))
                                aux += Convert.ToInt32(value);
                        }

                        chartAlocDisp.Series[lines[i]].Color = Color.Red;
                        dt = new System.Web.UI.DataVisualization.Charting.DataPoint(j, aux);
                        if (j == 1 || (j % 3 == 0 && j % 2 != 0)) dt.Label = "(" + j + ")" + aux + "h";
                        if ((collumnDate.DayOfWeek != DayOfWeek.Saturday && collumnDate.DayOfWeek != DayOfWeek.Sunday)
                                    && (!feriados.Contains(collumnDate.Date)))
                        {
                            dt.LabelAngle = 90;
                            dt.LabelBackColor = Color.FromArgb(255, 227, 227);
                            chartAlocDisp.Series[lines[i]].Points.Add(dt);
                        }
                    }
                    else
                    {
                        string value = "" + devForce[0][j];
                        chartAlocDisp.Series[lines[i]].Color = Color.Blue;
                        dt = new System.Web.UI.DataVisualization.Charting.DataPoint(j, string.IsNullOrEmpty(value) ? 0 : Convert.ToDouble(devForce[0][j]));
                        if (j == 0 || j % 2 == 0) dt.Label = "("+j+")" + devForce[0][j] + "h";
                        if ((collumnDate.DayOfWeek != DayOfWeek.Saturday && collumnDate.DayOfWeek != DayOfWeek.Sunday)
                                    && (!feriados.Contains(collumnDate.Date)))
                        {
                            dt.LabelAngle = -90;
                            dt.LabelBackColor = Color.FromArgb(211, 230, 255); 
                            chartAlocDisp.Series[lines[i]].Points.Add(dt);
                        }
                    }
                }

            }
        }

        private void PreencherCombo(IEnumerable<DemandModel> demandModels)
        {
            DateTime? dtInicioPeriodo = demandModels.Min(x => x.EstimatedStart);
            DateTime? dtFinalPeriodo = demandModels.Max(x => x.EstimatedConclude);

            while (dtInicioPeriodo.Value.Date <= dtFinalPeriodo.Value.Date)
            {
                cboMonths.Items.Add(new ListItem(dtInicioPeriodo.Value.Month + "/" + dtInicioPeriodo.Value.Year, dtInicioPeriodo.Value.Month + "/" + dtInicioPeriodo.Value.Year));
                dtInicioPeriodo = dtInicioPeriodo.Value.AddMonths(1);
            }
        }

        private void AdicionarGridHorasDisponiveis(DataTable demandas, GridView grd)
        {
            List<DeveloperModel> devsCDSB =
                    this.Presenter.Developers.ToList().FindAll(
                    delegate(DeveloperModel md)
                    {
                        bool forTeam = md.DeveloperTeam != "Suporte 3º Nível";
                        bool forMission = (md.Mission == Mission.Developer);
                        bool forCDSB = (md.DeveloperTeam.ToLower().Contains("time"));

                        return (forTeam && forMission && forCDSB);
                    });

            List<DeveloperModel> devs7Comm =
                this.Presenter.Developers.ToList().FindAll(
                delegate(DeveloperModel md)
                {
                    bool forTeam = md.DeveloperTeam != "Suporte 3º Nível";
                    bool forMission = (md.Mission == Mission.Developer);
                    bool forCDSB = (md.DeveloperTeam == "7COMm-VCoding");


                    //HC
                    bool list = (md.DeveloperName != "Ubiratan Radanovic Vieira");

                    return (forTeam && forMission && forCDSB && list);
                });

            //Adicionar GRID ForçaDesenvolvimento
            grd = new GridView();
            grd.Attributes.Add("bordercolor", "#000000");
            grd.AutoGenerateColumns = true;
            grd.ID = "HORAS DISPONIVEIS:";

            DataTable dt = new DataTable("developers");
            dt.Columns.Add("NAME");

            for (int i = 1; i <= System.DateTime.DaysInMonth(inicioPeriodo.Year, inicioPeriodo.Month); i++)
            {
                dt.Columns.Add("" + i);
            }

            DataRow row = null;
            row = dt.NewRow();
            row["NAME"] = string.Empty;
            for (int i = 1; i <= System.DateTime.DaysInMonth(inicioPeriodo.Year, inicioPeriodo.Month); i++)
            {
                int j = i - 1;
                DateTime tmStart = inicioPeriodo.AddDays(j);

                if ((tmStart.DayOfWeek == DayOfWeek.Saturday || tmStart.DayOfWeek == DayOfWeek.Sunday)
                                    || (this.Presenter.getFeriados().Contains(tmStart.Date)))
                {
                    row[i] = string.Empty;
                }
                else
                {
                    int hoursCDSB = devsCDSB.FindAll(delegate(DeveloperModel d)
                    {
                        List<DateTime> lstDataInterna = new List<DateTime>();

                        d.Dayof.ForEach(delegate(string strData)
                        {
                            lstDataInterna.Add(DateTime.Parse(strData.Split('|')[0]));
                        });

                        bool porFolga = lstDataInterna.Contains(tmStart.Date);
                        bool porFerias = (
                            (d.StartFreeDaysPaid.HasValue && d.FinishFreeDaysPaid.HasValue)
                            &&
                            (tmStart.Date >= d.StartFreeDaysPaid.Value.Date && tmStart.Date <= d.FinishFreeDaysPaid.Value.Date)
                                            );

                        bool porInicio = false;

                        if (d.DeveloperStartAt.HasValue)
                            porInicio = tmStart.Date < d.DeveloperStartAt.Value.Date;

                        return (!porFolga && !porFerias && !porInicio);

                    }).Count;

                    int hours7Comm = devs7Comm.FindAll(delegate(DeveloperModel d)
                    {
                        List<DateTime> lstDataInterna = new List<DateTime>();

                        d.Dayof.ForEach(delegate(string strData)
                        {
                            lstDataInterna.Add(DateTime.Parse(strData.Split('|')[0]));
                        });

                        bool porFolga = lstDataInterna.Contains(tmStart.Date);
                        bool porFerias = (
                            (d.StartFreeDaysPaid.HasValue && d.FinishFreeDaysPaid.HasValue)
                            &&
                            (tmStart.Date >= d.StartFreeDaysPaid.Value.Date && tmStart.Date <= d.FinishFreeDaysPaid.Value.Date)
                                            );

                        bool porInicio = false;

                        if (d.DeveloperStartAt.HasValue)
                            porInicio = tmStart.Date < d.DeveloperStartAt.Value.Date;

                        return (!porFolga && !porFerias && !porInicio);
                    }).Count;

                    hoursCDSB = hoursCDSB * 8;
                    hours7Comm = hours7Comm * 8;

                    int aux = 0;
                    foreach (DataRow item in demandas.Rows)
                    {
                        string value = item[tmStart.Day + 2].ToString();
                        if (!string.IsNullOrEmpty(value))
                            aux += Convert.ToInt32(value);
                    }

                    row[i] = (hoursCDSB + hours7Comm) - aux;
                }
            }

            dt.Rows.Add(row);

            dt.DefaultView.RowFilter = "";
            grd.ShowHeader = false;
            grd.DataSource = dt.DefaultView;
            grd.RowDataBound += new GridViewRowEventHandler(grd_RowDesenvolvimentoDataBound);
            grd.DataBind();



            grd.HorizontalAlign = HorizontalAlign.Center;
            this.parent.Controls.Add(grd);
            this.parent.Controls.Add(new LiteralControl("<br/>"));
            this.parent.Controls.Add(new LiteralControl("</div>"));
        }

        private DataView AdicionarGridForcaDesenvolvimento(GridView grd)
        {
            List<DeveloperModel> devsCDSB =
                    this.Presenter.Developers.ToList().FindAll(
                    delegate(DeveloperModel md)
                    {
                        bool isActive = md.IsActive;
                        bool forTeam = md.DeveloperTeam != "Suporte 3º Nível";
                        bool forMission = (md.Mission == Mission.Developer);
                        bool forCDSB = (md.DeveloperTeam.ToLower().Contains("time"));

                        return (forTeam && forMission && forCDSB && isActive);
                    });

            List<DeveloperModel> devs7Comm =
                this.Presenter.Developers.ToList().FindAll(
                delegate(DeveloperModel md)
                {
                    bool forTeam = md.DeveloperTeam != "Suporte 3º Nível";
                    bool forMission = (md.Mission == Mission.Developer);
                    bool forCDSB = (md.DeveloperTeam == "7COMm-VCoding");


                    //HC
                    bool list = (md.DeveloperName != "Ubiratan Radanovic Vieira");

                    return (forTeam && forMission && forCDSB && list);
                });

            //Adicionar GRID ForçaDesenvolvimento
            grd = new GridView();
            grd.Attributes.Add("bordercolor", "#000000");
            grd.AutoGenerateColumns = true;
            grd.ID = "FORÇA DESENVOLVIMENTO:";

            DataTable dt = new DataTable("developers");
            dt.Columns.Add("NAME");            

            for (int i = 1; i <= System.DateTime.DaysInMonth(inicioPeriodo.Year, inicioPeriodo.Month); i++)
            {
                dt.Columns.Add("" + i);
            }

            DataRow row = null;
            row = dt.NewRow();
            row["NAME"] = string.Empty;
            for (int i = 1; i <= System.DateTime.DaysInMonth(inicioPeriodo.Year, inicioPeriodo.Month); i++)
            {
                int j = i - 1;
                DateTime tmStart = inicioPeriodo.AddDays(j);

                if ((tmStart.DayOfWeek == DayOfWeek.Saturday || tmStart.DayOfWeek == DayOfWeek.Sunday)
                                    || (this.Presenter.getFeriados().Contains(tmStart.Date)))
                { 
                    row[i] = string.Empty; 
                }
                else
                {
                    int hoursCDSB = devsCDSB.FindAll(delegate(DeveloperModel d)
                    {
                        List<DateTime> lstDataInterna = new List<DateTime>();

                        d.Dayof.ForEach(delegate(string strData)
                        {
                            lstDataInterna.Add(DateTime.Parse(strData.Split('|')[0]));
                        });

                        bool porFolga = lstDataInterna.Contains(tmStart.Date);
                        bool porFerias = (
                            (d.StartFreeDaysPaid.HasValue && d.FinishFreeDaysPaid.HasValue)
                            &&
                            (tmStart.Date >= d.StartFreeDaysPaid.Value.Date && tmStart.Date <= d.FinishFreeDaysPaid.Value.Date)
                                            );

                        bool porInicio = false;

                        if (d.DeveloperStartAt.HasValue)
                            porInicio = tmStart.Date < d.DeveloperStartAt.Value.Date;

                        return (!porFolga && !porFerias && !porInicio);

                    }).Count;

                    int hours7Comm = devs7Comm.FindAll(delegate(DeveloperModel d)
                    {
                        List<DateTime> lstDataInterna = new List<DateTime>();

                        d.Dayof.ForEach(delegate(string strData)
                        {
                            lstDataInterna.Add(DateTime.Parse(strData.Split('|')[0]));
                        });

                        bool porFolga = lstDataInterna.Contains(tmStart.Date);
                        bool porFerias = (
                            (d.StartFreeDaysPaid.HasValue && d.FinishFreeDaysPaid.HasValue)
                            &&
                            (tmStart.Date >= d.StartFreeDaysPaid.Value.Date && tmStart.Date <= d.FinishFreeDaysPaid.Value.Date)
                                            );

                        bool porInicio = false;

                        if (d.DeveloperStartAt.HasValue)
                            porInicio = tmStart.Date < d.DeveloperStartAt.Value.Date;

                        return (!porFolga && !porFerias && !porInicio);
                    }).Count;

                    hoursCDSB = hoursCDSB * 8;
                    hours7Comm = hours7Comm * 8;

                    row[i] = hoursCDSB + hours7Comm;
                }
            }

            dt.Rows.Add(row);

            dt.DefaultView.RowFilter = "";
            grd.ShowHeader = false;
            grd.DataSource = dt.DefaultView;
            grd.RowDataBound += new GridViewRowEventHandler(grd_RowDesenvolvimentoDataBound);
            grd.DataBind();

            
            
            grd.HorizontalAlign = HorizontalAlign.Center;            
            this.parent.Controls.Add(grd);

            return dt.DefaultView;
        }

        private void AdicionarGridTotalAtiva(DataTable dt, GridView grd, IEnumerable<DemandModel> demands)
        {
            //Adicionar GRID TotalAtiva
            grd = new GridView();
            grd.Attributes.Add("bordercolor", "#000000");
            grd.AutoGenerateColumns = true;
            grd.ID = "PLANEJADAS:";

            string filter = string.Empty;

            List<DemandModel> ativas = demands.ToList().FindAll(delegate(DemandModel dm)
            {
                return dm.State == "Ativa";
            });

            for (int i = 0; i < ativas.Count; i++)
            {
                if (i != 0) filter += ",";
                filter += ativas[i].ID;
            }

            if(ativas.Count != 0)
                dt.DefaultView.RowFilter = "ID IN (" + filter + ")";
            else
                dt.DefaultView.RowFilter = "ID = '0'";

            grd.RowDataBound += new GridViewRowEventHandler(grd_RowDataBound);
            grd.DataSource = dt.DefaultView;
            grd.ShowFooter = true;
            grd.ShowHeader = false;
            array = new int[dt.Columns.Count];
            grd.DataBind();

            foreach (GridViewRow r in grd.Rows)
            {
                if (r.RowType == DataControlRowType.DataRow)
                    r.Visible = false;
            }

            
            
            grd.HorizontalAlign = HorizontalAlign.Center;
            this.parent.Controls.Add(grd);
            
        }

        private void AdicionarGridTotalGeral(DataTable dt, GridView grd)
        {
            //Adicionar GRID TotalGeral
            grd = new GridView();
            grd.Attributes.Add("bordercolor", "#000000");
            grd.AutoGenerateColumns = true;
            grd.ID = "DIA:";
            dt.DefaultView.RowFilter = "";
            grd.RowDataBound += new GridViewRowEventHandler(grd_RowDataBound);
            grd.DataSource = dt.DefaultView;
            grd.ShowFooter = true;            
            array = new int[dt.Columns.Count];
            grd.DataBind();

            foreach (GridViewRow r in grd.Rows)
            {
                if (r.RowType == DataControlRowType.DataRow)
                    r.Visible = false;
            }

            string span = "<div style='width:100%; background-color:#E1ECEF; border: solid; border-width:1px; border-color:#000000; font-family:Verdana;font-size:Small;font-weight:bold;text-align:left;'>{0}";
            this.parent.Controls.Add(new LiteralControl(string.Format(span, "TOTAL GERAL:" + "<br/><br/>")));
            
            
            grd.HorizontalAlign = HorizontalAlign.Center;
            this.parent.Controls.Add(grd);            
        }

        private bool inData(DateTime? EstimatedStart, DateTime? EstimatedConclude, DateTime dataColuna)
        {
            return (dataColuna.Date >= EstimatedStart.Value.Date && dataColuna.Date <= EstimatedConclude.Value.Date);
        }

        void grd_RowDesenvolvimentoDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                e.Row.Style.Add("text-align", "center");
                e.Row.Style.Add("font-family", "Verdana");
                e.Row.Style.Add("font-size", "X-Small");
                e.Row.Cells[0].Width = 200;
                e.Row.Cells[0].HorizontalAlign = HorizontalAlign.Left;
                e.Row.Cells[0].Text = (sender as GridView).ID;

                if ((sender as GridView).ID == "HORAS DISPONIVEIS:")
                {
                    
                }
                else
                {
                    e.Row.Style.Add("background-color", "#99CCFF");
                }

                for (int i = 1; i < e.Row.Cells.Count; i++)
                {
                    e.Row.Cells[i].Width = 35;
                    array[i] += Convert.ToInt32((e.Row.Cells[i].Text.Replace("h", "").Replace("&nbsp;", "0")) ?? "0");

                    if ((sender as GridView).ID == "HORAS DISPONIVEIS:")
                    {
                        if(e.Row.Cells[i].Text.IndexOf("-") != -1)
                            e.Row.Cells[i].Style.Add("background-color", "#33CC33");
                        else
                            e.Row.Cells[i].Style.Add("background-color", "#FF3300");
                    }

                    if (this.finaldeSemana(inicioPeriodo.AddDays(i - 1)) || this.Presenter.getFeriados().Contains(inicioPeriodo.AddDays(i - 1)))
                        e.Row.Cells[i].Style.Add("background-color", "#FFFFFF");
                }
            }
        }

        public bool finaldeSemana(DateTime data)
        {
            return data.DayOfWeek == DayOfWeek.Saturday || data.DayOfWeek == DayOfWeek.Sunday;
        }

        void grd_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.Header)
            {
                e.Row.Attributes.Add("cellspacing", "1");
                e.Row.Attributes.Add("cellpadding", "2");
                e.Row.Attributes.Add("background-color", "#333333");

                e.Row.Style.Add("text-align", "center");
                e.Row.Style.Add("background-color", "#CFCFCF");
                e.Row.Style.Add("font-family", "Verdana");
                e.Row.Style.Add("font-size", "X-Small");

                e.Row.Cells[2].HorizontalAlign = HorizontalAlign.Left;

                e.Row.Cells[2].Text = (sender as GridView).ID;
                e.Row.Cells[2].Width = 200;
            }

            e.Row.Controls[0].Visible = false;
            e.Row.Controls[1].Visible = false;

            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                DemandModel model = demandas.ToList().Find((delegate(DemandModel d){return (d.ID == e.Row.Cells[2].Text);}));
                string descricao = string.Empty;
                DeveloperModel developer = this.Presenter.FindDeveloperOf(model.Revision);
                if(developer != null)
                    descricao = "Status: " + model.State + " - Desenvolvedor: " + developer.DeveloperName + " - Simultânea: " + ((model.IsSimultaneous) ? "Sim" : "Não");
                else
                    descricao = "Status: " + model.State + " - Simultânea: " + ((model.IsSimultaneous) ? "Sim" : "Não");
                e.Row.Cells[2].Text = "<a title='" + descricao + "'>" + e.Row.Cells[2].Text + "</a>";
                e.Row.Style.Add("text-align", "center");
                e.Row.Cells[2].HorizontalAlign = HorizontalAlign.Left;
                e.Row.Style.Add("background-color", "#FFFFFF");
                e.Row.Style.Add("font-family", "Verdana");
                e.Row.Style.Add("font-size", "X-Small");

                for (int i = 3; i < e.Row.Cells.Count; i++)
                {
                    e.Row.Cells[i].Width = 35;
                    if (this.finaldeSemana(inicioPeriodo.AddDays(i - 3)) || this.Presenter.getFeriados().Contains(inicioPeriodo.AddDays(i - 3)))
                        e.Row.Cells[i].Style.Add("background-color", "#FFFFFF");
                    else
                        array[i] += Convert.ToInt32((e.Row.Cells[i].Text.Replace("h", "").Replace("&nbsp;", "0")) ?? "0");
                }
                
            }

            if (e.Row.RowType == DataControlRowType.Footer)
            {
                e.Row.Cells[2].Width = 200;                
                e.Row.Style.Add("text-align", "center");
                e.Row.Style.Add("background-color", "#FFFF99");
                e.Row.Style.Add("font-family", "Verdana");
                e.Row.Style.Add("font-size", "X-Small");
                e.Row.Style.Add("font-weight", "bold");

                e.Row.Cells[2].HorizontalAlign = HorizontalAlign.Left;

                if (((GridView)sender).ID == "DIA:")
                {
                    e.Row.Style.Add("background-color", "#FFFF99");
                    e.Row.Cells[2].Text = "HORAS ALOCADAS:";
                }
                else if (((GridView)sender).ID == "PLANEJADAS:")
                {
                    e.Row.Style.Add("background-color", "#FFCC66");
                    e.Row.Cells[2].Text = "HORAS PLANEJADAS:";
                }
                else
                    e.Row.Cells[2].Text = "Total:";

                for (int i = 3; i < e.Row.Cells.Count; i++)
                {
                    e.Row.Cells[i].Width = 35;
                    if (this.finaldeSemana(inicioPeriodo.AddDays(i - 3)) || this.Presenter.getFeriados().Contains(inicioPeriodo.AddDays(i - 3)))
                        e.Row.Cells[i].Style.Add("background-color", "#FFFFFF");
                    else
                        e.Row.Cells[i].Text = array[i].ToString();
                    
                }
            }

        }

        private string RetornaTeamProject(string project)
        {
            if (this.Presenter.TeamProjectsIMercado.Contains(project)) return "IMERCADO";            
            if (this.Presenter.TeamProjectsSinacor.Contains(project)) return "SINACOR";
            if (this.Presenter.TeamProjectsSiteBVMF.Contains(project)) return "SITEBMFBOVESPA";

            return string.Empty;
        }

        private void ExibirObservacao(string obs)
        {
            this.LblObsOrdenacao.Text = obs;
            this.LblObsOrdenacao.Visible = this.LblObsOrdenacao.Text.Length > 0 ? true : false;
        }

        private bool inIntervalo(DateTime? EstimatedStart, DateTime? EstimatedConclude, DateTime tmStart)
        {
            //inicio
            bool porInicio =
                (EstimatedStart.Value.Date <= tmStart.Date && EstimatedConclude.Value.Date >= tmStart.Date);

            //final
            bool porFinal =
                (EstimatedStart.Value.Date >= tmStart.Date && tmStart.Month == EstimatedStart.Value.Month);

            return (porInicio || porFinal);
        }

        #region IDiscriminatorDemand Members

        void IDiscriminatorDemand.ExibirFila(IEnumerable<CDSBDemandControl.Model.DemandModel> demandModels)
        {
            throw new NotImplementedException();
        }

        void IDiscriminatorDemand.ExibirEsteira(IEnumerable<CDSBDemandControl.Model.DemandModel> demandModels)
        {
            throw new NotImplementedException();
        }

        void IDiscriminatorDemand.ExibirRanking(IEnumerable<CDSBDemandControl.Model.DeveloperModel> developers, IEnumerable<CDSBDemandControl.Model.DeveloperModel> leaders, IEnumerable<CDSBDemandControl.Model.DeveloperModel> focalpoints)
        {
            throw new NotImplementedException();
        }

        void IDiscriminatorDemand.ExibirAtrasos(IEnumerable<CDSBDemandControl.Model.DemandModel> PendingDemands, IEnumerable<CDSBDemandControl.Model.DemandModel> Concludeddemands)
        {
            throw new NotImplementedException();
        }

        void IDiscriminatorDemand.ExibirFaturamento(List<CDSBDemandControl.Model.BillingModel> billing, bool canSeeBilling)
        {
            throw new NotImplementedException();
        }

        void IDiscriminatorDemand.ExibirScenariosAndTasks(List<CDSBDemandControl.Model.ScenarioModel> scenarios)
        {
            throw new NotImplementedException();
        }

        void IDiscriminatorDemand.ExibirCodeReview(IEnumerable<CDSBDemandControl.Model.DemandModel> WorkItemsWithCodeReview, IEnumerable<CDSBDemandControl.Model.DemandModel> WorkItemsWithoutCodeReview)
        {
            throw new NotImplementedException();
        }

        void IDiscriminatorDemand.ExibirBugsdeProducao(IEnumerable<CDSBDemandControl.Model.DemandModel> demandModels)
        {
            throw new NotImplementedException();
        }

        void IDiscriminatorDemand.ExibirListaDisp(IEnumerable<CDSBDemandControl.Model.DemandModel> list, IEnumerable<CDSBDemandControl.Model.DeveloperModel> modelAusencias, List<DateTime> fer)
        {
            throw new NotImplementedException();
        }

        void IDiscriminatorDemand.ExibirBugsdeProducaoUltimoMes(List<CDSBDemandControl.Model.DemandModel> BugList)
        {
            throw new NotImplementedException();
        }

        void IDiscriminatorDemand.ExibirFactoryWaitingList(List<CDSBDemandControl.Model.BillingModel> Billing, bool AllowsShow)
        {
            throw new NotImplementedException();
        }

        void IDiscriminatorDemand.ExibirFactoryProductionList(List<BillingModel> billing, bool canSeeBilling)
        {
            throw new NotImplementedException();
        }

        void IDiscriminatorDemand.ExibirSolicitacoesSites(List<CDSBDemandControl.Model.DemandModel> demandModels)
        {
            throw new NotImplementedException();
        }

        void IDiscriminatorDemand.ExibirManagementTeamTasks(List<CDSBDemandControl.Model.DemandModel> demandModels)
        {
            throw new NotImplementedException();
        }

        #endregion
    }
}
